package com.general.message.push.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
import com.general.common.exception.ServiceException;
import com.general.common.utils.AsyncTaskHelper;
import com.general.common.utils.StringUtils;
import com.general.message.push.sms.request.Andon;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component
public class SmsSupport {
    @Resource
    private JdbcTemplate jdbcTemplate;
    public static void main(String[] args) {
        SmsSupport smsSupport = new SmsSupport();
        smsSupport.init();
        Andon andon = new Andon("王首都", "层压", "缺料");
        smsSupport.sendSms(SmsTemplate.ANDON, "17855482218", andon);
    }

    @Value("${aliyun.sms.accessKey}")
    private String accessKey = "LTAI5tGwtXYc9xCkS2WDPAB8";
    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret = "SsbaQuxiWsASHIOLCeu6aZLYlZDi30";
//    @Value("${aliyun.sms.accessKey}")
//    private String accessKey = "LTAI5t5kYqHaELVhSf9fdtGy";
//    @Value("${aliyun.sms.accessKeySecret}")
//    private String accessKeySecret = "o4b8XzFyu8n2SAwRIVgzYEguz26f71";
    private Client client = null;

    @PostConstruct
    public void init() {
        Config config = new Config();
        config.setAccessKeyId(accessKey);
        config.setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";

        try {
            client = new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendSms(SmsTemplate template, String phoneNumber, Object params) {
        if (template == null) {
            throw new ServiceException("空的模板");
        }
        if (params == null) {
            throw new ServiceException("空的请求参数");
        }
        if (StringUtils.isBlank(phoneNumber) || phoneNumber.length() != 11) {
            throw new ServiceException("错误的接收号码：" + phoneNumber);
        }
        if (!params.getClass().isAssignableFrom(template.getClazz())) {
            throw new ServiceException("请求参数异常");
        }

        // 1min内同一个按钮盒只允许发送一条短信
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumber);
        request.setSignName(template.signName);
        request.setTemplateCode(template.templateCode);

        String jsonParams = new Gson().toJson(params);
        request.setTemplateParam(jsonParams);

        try {
            SendSmsResponse response = client.sendSmsWithOptions(request, new RuntimeOptions());
            System.out.println(response);
            System.out.println(response.getBody().getMessage());
            System.out.println(response.getStatusCode());
            AsyncTaskHelper.getInstance().execute(() -> {
                String sql = "insert into sms_send_log (`code`, template, template_params, receive_phone_number, response, `module`) values(?, ?, ?, ?, ?, 'andon')";
                jdbcTemplate.update(sql, response.getStatusCode(), template.templateCode, jsonParams, phoneNumber, response.body.message);
            });
        } catch (TeaException e) {
            // 错误 message
            System.out.println(e.getMessage());
            // 诊断地址
            System.out.println(e.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(e.message);
        } catch (Exception e) {
            TeaException error = new TeaException(e.getMessage(), e);
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

}
